//
//  SecondViewController.m
//  OSChina
//
//  Created by 林涛 on 14/12/23.
//  Copyright (c) 2014年 林涛. All rights reserved.
//

#import "OSPostsViewController.h"
#import "OSNetworkRequest.h"
#import "OSTableViewDataSourceObject.h"
#import "OSPostsTableViewCell.h"
#import "MJRefresh.h"
@interface OSPostsViewController ()

@property (strong, nonatomic) IBOutlet UISegmentedControl  *segmentedControl;
@property (strong, nonatomic) OSTableViewDataSourceObject  *tableViewDataSourceObject;
@property (strong, nonatomic) NSArray                      *answerList;
@property (assign, nonatomic) NSInteger pageCount;
@end

@implementation OSPostsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageCount = 20;
    [self setup];
}

- (void)setup
{
    [super setup];
    TableViewCellConfigureBlock block = ^(OSPostsTableViewCell *cell, id item,NSIndexPath *indexPath){
        [cell configWith:item];
    };
    self.tableViewDataSourceObject    = [[OSTableViewDataSourceObject alloc]initWithItems:[NSMutableArray array] cellIdentifier:[OSPostsTableViewCell identifier] configureCellBlock:block];
    self.tableView.dataSource         = self.tableViewDataSourceObject;
}

- (void)headerRereshing
{
    [self requestNews];
}

- (void)footerRereshing
{
    [self requestNews];
}

- (void)requestNews
{
    NSString *catalog = [NSString stringWithFormat:@"%ld",self.segmentedControl.selectedSegmentIndex + 1];
    NSString *pageIndex = [NSString stringWithFormat:@"%ld",self.pageCount / 20];
    [OSNetworkRequest answerLisRequestWithCount:@"20" catalog:catalog pageIndex:pageIndex success:^(id result) {
        self.pageCount += 20;
        NSDictionary *dic = result[@"posts"];
        [self.tableViewDataSourceObject.items addObjectsFromArray:dic[@"post"]];
        [self refreshTableView];
    } failure:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)segmentedAction:(UISegmentedControl *)sender {
    self.pageCount = 20;
    [self.tableViewDataSourceObject.items removeAllObjects];
    [self.tableView reloadData];
    [self.tableView headerBeginRefreshing];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([sender isKindOfClass:[OSPostsTableViewCell class]]) {
        OSPostsTableViewCell *cell = sender;
        UIViewController *vc = segue.destinationViewController;
        vc.title = [NSString stringWithFormat:@"%@",[self segmentTitle]];
        [vc setValue:cell.model forKey:@"infoModel"];
        [vc setValue:api_post_detail forKey:@"urlPath"];
         [vc setValue:@"post" forKey:@"dataType"];
    }
}

- (NSString *)segmentTitle
{
    return [self.segmentedControl titleForSegmentAtIndex:self.segmentedControl.selectedSegmentIndex];
}


@end
